from django import forms
from django.contrib.auth.decorators import login_required
from .models import Article, Category, Tag

class ArticleForm(forms.ModelForm):
    """文章编辑表单"""
    
    class Meta:
        model = Article
        fields = ['title', 'category', 'tags', 'excerpt', 'content', 'featured_image', 'status', 'is_featured']
        widgets = {
            'title': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': '请输入文章标题'
            }),
            'excerpt': forms.Textarea(attrs={
                'class': 'form-control',
                'rows': 3,
                'placeholder': '请输入文章摘要（可选）'
            }),
            'content': forms.Textarea(attrs={
                'class': 'form-control markdown-editor',
                'rows': 20,
                'placeholder': '请输入文章内容，支持Markdown语法',
                'required': False  # 移除HTML5 required属性，使用Django验证
            }),
            'category': forms.Select(attrs={
                'class': 'form-select'
            }),
            'tags': forms.CheckboxSelectMultiple(attrs={
                'class': 'form-check-input'
            }),
            'featured_image': forms.FileInput(attrs={
                'class': 'form-control',
                'accept': 'image/*'
            }),
            'status': forms.Select(attrs={
                'class': 'form-select'
            }),
            'is_featured': forms.CheckboxInput(attrs={
                'class': 'form-check-input'
            })
        }
        
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['category'].queryset = Category.objects.all()
        self.fields['tags'].queryset = Tag.objects.all()
        self.fields['category'].empty_label = "选择分类"
        
        # 设置字段标签
        self.fields['title'].label = '标题'
        self.fields['category'].label = '分类'
        self.fields['tags'].label = '标签'
        self.fields['excerpt'].label = '摘要'
        self.fields['content'].label = '内容'
        self.fields['featured_image'].label = '特色图片'
        self.fields['status'].label = '状态'
        self.fields['is_featured'].label = '推荐文章'
        
        # 移除content字段的required属性，避免与CodeMirror冲突
        self.fields['content'].required = False  # 彻底移除required属性
        
    def clean_content(self):
        """自定义content字段验证"""
        content = self.cleaned_data.get('content')
        if not content or not content.strip():
            raise forms.ValidationError('文章内容不能为空')
        return content